//
//  SettingsViewController.m
//  XDCommonApp
//
//  Created by wanglong8889@126.com on 14-6-12.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "SettingsViewController.h"
#import "PersonCenterCell.h"
#import "aboutViewController.h"
#import "changePasswordViewController.h"
#import "loginViewController.h"

#import "APService.h"

@implementation SettingsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int size = [self sizeOfFolder:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
        NSString * lastSize = @"";
        if (size < (1024*1024)) {
            lastSize = [NSString stringWithFormat:@"%.1fKB",size/1024.0f];
        }else if(size > (1024*1024)){
            lastSize = [NSString stringWithFormat:@"%.1fMB",size/1024.0f/1024.0f];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            cacheLabel.text = lastSize;
        });
    });
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.titleLabel.text = @"设置";
   
    mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, self.contentView.frame.size.height-UI_TAB_BAR_HEIGHT)];
    mytableView.backgroundColor = [UIColor clearColor];
    mytableView.delegate = self;
    mytableView.dataSource = self;
    mytableView.separatorColor =UIColorFromRGB(0xe2e0da);
    [self.contentView addSubview:mytableView];
    if (ISLOGING){
        dataArray = @[@"给个好评",@"清除缓存",@"版本检查",@"关于小鬼当佳",@"修改密码",@"退出登录"];

    }else{
        dataArray = @[@"给个好评",@"清除缓存",@"版本检查",@"关于小鬼当佳"];


    }
    
    UIView *lineHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 20, UI_SCREEN_WIDTH, .5f)];
    lineHeader.backgroundColor = UIColorFromRGB(0xe2e0da);
    [mytableView addSubview:lineHeader];
    downUrl = [[NSString alloc]init];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return  [dataArray count];
    }
    return  [dataArray count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return  20.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return  20.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 20)];
    headerView.backgroundColor = [UIColor clearColor];
    return  headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 20)];
    headerView.backgroundColor = [UIColor clearColor];
    return  headerView;
}

-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellid = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }

    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            cacheLabel = [[UILabel alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH -120, 5, 80, 34)];
            cacheLabel.tag =5000;

            cacheLabel.font =[UIFont systemFontOfSize:14.5];
            cacheLabel.textColor = UIColorFromRGB(0x867c71);
            cacheLabel.textAlignment =NSTextAlignmentRight;
            [cell.contentView addSubview:cacheLabel];
        }
        
        cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
        cell.textLabel.textColor = UIColorFromRGB(0x867c71);
        cell.textLabel.font = [UIFont systemFontOfSize:15.5];
        UIImageView *arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_cell"]];
        arrow.frame = CGRectMake((UI_SCREEN_WIDTH-15-7), 15, 7, 12);
        [cell.contentView addSubview:arrow];
        
        if (indexPath.row == 5) {
            UIView *lineFooter = [[UIView alloc]initWithFrame:CGRectMake(0,45-.5f, UI_SCREEN_WIDTH, .5f)];
            lineFooter.backgroundColor = UIColorFromRGB(0xe2e0da);
            [cell.contentView addSubview:lineFooter];
        }
    }
    return cell;
}

- (NSInteger)numberOfSections
{
    return  1;
}
- (NSInteger)numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return  6;
    }
    return  6;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    switch (indexPath.row) {
        case 0:{
            [self goodComment];
             break;
        }
        case 1:{
            [XDTools showTips:@"正在清理中..." toView:self.view];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                NSLog(@"files :%d",[files count]);
                for (NSString *p in files) {
                    NSError *error;
                    NSString *path = [cachPath stringByAppendingPathComponent:p];
                    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    cacheLabel.text = @"0KB";
                });
            });
            
            break;
        }
        case 2:{
            downUrl = [[NSString alloc] init];
            cString = [[NSString alloc] init];
            [self updateVerson];
            break;
        }
        case 3:{
            aboutViewController *aboutUs = [[aboutViewController alloc]init];
            [self.navigationController pushViewController:aboutUs animated:YES];
            break;
        }
        case 4:{
            changePasswordViewController *changePWD = [[changePasswordViewController alloc]init];
            [self.navigationController pushViewController:changePWD animated:YES];
            break;
        }
        case 5:{
            UIAlertView *toComfirmLogOut = [[UIAlertView alloc]initWithTitle:nil message:@"您确认要退出？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            toComfirmLogOut.delegate = self;
            toComfirmLogOut.tag = 111;
            [toComfirmLogOut show];
            break;
        }
        case  6:{
            loginViewController *login = [[loginViewController alloc]init];
            [self.navigationController pushViewController:login animated:YES];
            break;
        }
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag ==111) {
        if (buttonIndex == 0) {
            
        }else if (buttonIndex == 1){
            [self logOutAction];
        }
    }else if (alertView.tag == 222){
        if (buttonIndex == 0) {
            NSURL *url = [NSURL URLWithString:downUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
    }else if (alertView.tag == 110){
        if (buttonIndex == 0) {
            NSURL *url = [NSURL URLWithString:downUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
//退出登录
-(void)logOutAction{
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    NSDictionary *requestDic = @{@"UID": [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID]};
    ASIHTTPRequest *request = [XDTools postRequestWithDict:requestDic API:API_LOGINOUT];
    __weak ASIHTTPRequest * mrequest = request;
    [request setTimeOutSeconds:12];
    [request setCompletionBlock:^{
        NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
        if ([[tmpDict objectForKey:@"status"] intValue] == 1) {
            [XDTools showTips:@"退出成功" toView: self.contentView];
            [self removeUserInfo];

            [APService setTags:[NSSet setWithObject:@""] callbackSelector:nil object:nil];

            [self performSelector:@selector(backPrePage) withObject:nil afterDelay:1.0f];
        }else{
            [XDTools showTips:[tmpDict objectForKey:@"msg"] toView:self.contentView];
        }
    }];
    [request setFailedBlock:^{
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request startAsynchronous];
    
}


-(void)backPrePage
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)removeUserInfo
{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_ID];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_NAME];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_TOKEN];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_IPHONE];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_FACE];

}
//版本更新
-(void)updateVerson{
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
   
    ASIHTTPRequest * request =[XDTools postRequestWithDict:@{@"Type":@"ios"} API:API_GETVERSION] ;
    
    __weak ASIHTTPRequest * mrequest = request;
    
    [request setCompletionBlock:^{
        
        NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
        NSDictionary * returnDict =[tmpDict valueForKey:@"data"];
        NSString *oldVerson = [[NSString alloc] initWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
        NSString * newVerson = [NSString stringWithFormat:@"%@",returnDict[@"Version"]];
        if ([oldVerson isEqualToString:newVerson])
        {
            [XDTools showTips:@"已经是最新版本" toView:self.view];
            return;
        }
        downUrl =[returnDict objectForKey:@"Url"];
        if (0) {
            UIAlertView *alertForce = [[UIAlertView alloc]initWithTitle:@"版本更新" message:[returnDict objectForKey:@"Remark"]  delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新", nil];
            alertForce.tag = 110;
            [alertForce show];
        }else{
            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:[returnDict objectForKey:@"Remark"] delegate:self cancelButtonTitle:@"立即更新" otherButtonTitles:@"忽略本次", nil];
            al.tag = 222;
            
            for (UIView *view in al.subviews) {
                if ([view isKindOfClass:[UILabel class]]) {
                    
                    UILabel *labe = (UILabel *)view;
                    
                    labe.textAlignment = NSTextAlignmentLeft;
                }
            }
            [al show];
            
        }
        
        
    }];
    
    [request setFailedBlock:^{
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];
}
//给好评
-(void)goodComment{
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    
    ASIHTTPRequest * request =[XDTools postRequestWithDict:nil API:@"Index&a=appstoreScore"];
    
    __weak ASIHTTPRequest * mrequest = request;
    
    [request setCompletionBlock:^{
        
        NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
        if ([tmpDict[@"status"] intValue]==1){
            NSString * commentURl =[tmpDict[@"data"] objectForKey:@"Url"];
            NSURL *url = [NSURL URLWithString:commentURl];
            [[UIApplication sharedApplication] openURL:url];
        }else{
        }
    }];
    
    [request setFailedBlock:^{
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];
}
//计算缓存size
- (int)sizeOfFolder:(NSString*)folderPath
{
    NSArray *contents;
    NSEnumerator *enumerator;
    NSString *path;
    contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
    enumerator = [contents objectEnumerator];
    int fileSizeInt = 0;
    while (path = [enumerator nextObject]) {
        NSError *error;
        NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:path] error:&error];
        fileSizeInt +=[fattrib fileSize];
    }
    return fileSizeInt;
}
@end
